package work817;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Client {
  public static List<Clients> list = new ArrayList<>();
  static Scanner sc = new Scanner(System.in);

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    File file = new File("E:\\bdqn\\javaDemo\\save.bin");
    if (!file.exists()) {
      try {
        file.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    int orderId = 1;
    String continu = "Y";
    System.out.println("用户名：");
    String username = sc.next();
    System.out.println("请输入产品：");
    do {
      add(file, orderId, username);
      orderId++;
      System.out.println("是否继续：Y/N");
      continu = sc.next();
    } while (continu.equals("y") || continu.equals("Y"));
    save(file);
    double sum = 0;
    System.out.println("产品名\t\t单价\t\t数量");
    load(file);
    for (Clients clients : list) {
      System.out.println(clients.getOrders().getGoods().getName() + "\t" + clients.getOrders().getGoods().getPrice() + "\t" + clients.getOrders().getGoods().getCount());
      sum = sum + clients.getOrders().getGoods().getPrice() * clients.getOrders().getGoods().getCount();
    }
    System.out.println("订单总价" + sum);

  }

  public static void add(File file, int orderId, String username) {
    System.out.println("产品号：");
    int id = sc.nextInt();
    System.out.println("产品名称：");
    String name = sc.next();
    System.out.println("购买数量：");
    int count = sc.nextInt();
    System.out.println("产品单价：");
    double price = sc.nextDouble();
    list.add(new Clients(username, new Orders(orderId, new Goods(id, name, count, price))));
    System.out.println(list.size());
  }
  /**
   * 序列化
   * @param file
   */
  private static void save(File file) {
    ObjectOutputStream oos = null;
    try {
       oos = new ObjectOutputStream(new FileOutputStream(file));
      oos.writeObject(list);
    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      try {
        oos.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  /**
   * 反序列化
   * @param file
   */
  private static void load(File file) {
    ObjectInputStream ois = null;
    try {
     ois = new ObjectInputStream(new FileInputStream(file));
      list = (List<Clients>) ois.readObject();
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      try {
        ois.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
